package cn.j0n4than.accountingtool.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * 邮件类
 *
 * @author jonathan
 */
@Component
public class MailUtil {

    @Autowired
    private JavaMailSender sender;
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 简单邮件发送
     *
     * @param subject 邮件主题
     * @param to      收件人
     * @param content 邮件内容
     */
    public void simpleMailSend(String subject, String to, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setFrom(this.from);
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSentDate(new Date());
        simpleMailMessage.setText(content);
        sender.send(simpleMailMessage);
    }

    /**
     * 富文本邮件发送
     *
     * @param subject 邮件主题
     * @param to      收件人
     * @param content 邮件内容
     */
    public void mimeMessageSend(String subject, String to, String content) throws MessagingException {
        MimeMessage mimeMessage = sender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setFrom(this.from);
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setSentDate(new Date());
        mimeMessageHelper.setText(content, true);
        sender.send(mimeMessage);
    }
}
